/**
 * IndexedDB 数据库封装
 * 提供记忆组和记忆内容的增删改查功能
 */

class MemoryDatabase {
    constructor() {
        this.dbName = 'MemoryToolDB';
        this.version = 2;
        this.db = null;
    }

    // 初始化数据库
    async init() {
        return new Promise((resolve, reject) => {
            const request = indexedDB.open(this.dbName, this.version);

            request.onerror = () => {
                reject(new Error('数据库打开失败'));
            };

            request.onsuccess = () => {
                this.db = request.result;
                resolve(this.db);
            };

            request.onupgradeneeded = (event) => {
                const db = event.target.result;
                const oldVersion = event.oldVersion;
                
                // 创建记忆组表
                if (!db.objectStoreNames.contains('groups')) {
                    const groupStore = db.createObjectStore('groups', { 
                        keyPath: 'id', 
                        autoIncrement: true 
                    });
                    groupStore.createIndex('createTime', 'createTime', { unique: false });
                }

                // 创建记忆内容表
                if (!db.objectStoreNames.contains('memories')) {
                    const memoryStore = db.createObjectStore('memories', { 
                        keyPath: 'id', 
                        autoIncrement: true 
                    });
                    memoryStore.createIndex('groupId', 'groupId', { unique: false });
                    memoryStore.createIndex('day', 'day', { unique: false });
                    memoryStore.createIndex('groupDay', ['groupId', 'day'], { unique: false });
                }

                // 版本2升级：为现有组添加记忆开始时间
                if (oldVersion < 2) {
                    const transaction = event.target.transaction;
                    const groupStore = transaction.objectStore('groups');
                    const request = groupStore.getAll();
                    
                    request.onsuccess = () => {
                        const groups = request.result;
                        groups.forEach(group => {
                            if (!group.memoryStartTime) {
                                group.memoryStartTime = group.createTime; // 默认为创建时间
                                groupStore.put(group);
                            }
                        });
                    };
                }
            };
        });
    }

    // 确保数据库已初始化
    async ensureDB() {
        if (!this.db) {
            await this.init();
        }
        return this.db;
    }

    // 添加记忆组
    async addGroup(groupData) {
        const db = await this.ensureDB();
        const transaction = db.transaction(['groups'], 'readwrite');
        const store = transaction.objectStore('groups');
        
        return new Promise((resolve, reject) => {
            const request = store.add({
                name: groupData.name,
                color: groupData.color,
                createTime: groupData.createTime || new Date().toISOString()
            });
            
            request.onsuccess = () => resolve(request.result);
            request.onerror = () => reject(new Error('添加组失败'));
        });
    }

    // 获取所有记忆组
    async getAllGroups() {
        const db = await this.ensureDB();
        const transaction = db.transaction(['groups'], 'readonly');
        const store = transaction.objectStore('groups');
        
        return new Promise((resolve, reject) => {
            const request = store.getAll();
            request.onsuccess = () => resolve(request.result);
            request.onerror = () => reject(new Error('获取组列表失败'));
        });
    }

    // 根据ID获取记忆组
    async getGroup(groupId) {
        const db = await this.ensureDB();
        const transaction = db.transaction(['groups'], 'readonly');
        const store = transaction.objectStore('groups');
        
        return new Promise((resolve, reject) => {
            const request = store.get(groupId);
            request.onsuccess = () => resolve(request.result);
            request.onerror = () => reject(new Error('获取组失败'));
        });
    }

    // 更新记忆组
    async updateGroup(groupId, updateData) {
        const db = await this.ensureDB();
        const transaction = db.transaction(['groups'], 'readwrite');
        const store = transaction.objectStore('groups');
        
        return new Promise((resolve, reject) => {
            const getRequest = store.get(groupId);
            getRequest.onsuccess = () => {
                const group = getRequest.result;
                if (group) {
                    Object.assign(group, updateData);
                    const putRequest = store.put(group);
                    putRequest.onsuccess = () => resolve(putRequest.result);
                    putRequest.onerror = () => reject(new Error('更新组失败'));
                } else {
                    reject(new Error('组不存在'));
                }
            };
            getRequest.onerror = () => reject(new Error('获取组失败'));
        });
    }

    // 删除记忆组
    async deleteGroup(groupId) {
        const db = await this.ensureDB();
        const transaction = db.transaction(['groups', 'memories'], 'readwrite');
        const groupStore = transaction.objectStore('groups');
        const memoryStore = transaction.objectStore('memories');
        
        return new Promise((resolve, reject) => {
            // 先删除该组的所有记忆内容
            const memoryIndex = memoryStore.index('groupId');
            const memoryRequest = memoryIndex.getAll(groupId);
            
            memoryRequest.onsuccess = () => {
                const memories = memoryRequest.result;
                let deleteCount = 0;
                
                if (memories.length === 0) {
                    // 没有记忆内容，直接删除组
                    const groupRequest = groupStore.delete(groupId);
                    groupRequest.onsuccess = () => resolve();
                    groupRequest.onerror = () => reject(new Error('删除组失败'));
                } else {
                    // 删除所有记忆内容
                    memories.forEach(memory => {
                        const deleteRequest = memoryStore.delete(memory.id);
                        deleteRequest.onsuccess = () => {
                            deleteCount++;
                            if (deleteCount === memories.length) {
                                // 所有记忆内容删除完成，删除组
                                const groupRequest = groupStore.delete(groupId);
                                groupRequest.onsuccess = () => resolve();
                                groupRequest.onerror = () => reject(new Error('删除组失败'));
                            }
                        };
                        deleteRequest.onerror = () => reject(new Error('删除记忆内容失败'));
                    });
                }
            };
            memoryRequest.onerror = () => reject(new Error('获取记忆内容失败'));
        });
    }

    // 添加记忆内容
    async addMemory(memoryData) {
        const db = await this.ensureDB();
        const transaction = db.transaction(['memories'], 'readwrite');
        const store = transaction.objectStore('memories');
        
        return new Promise((resolve, reject) => {
            const request = store.add({
                groupId: memoryData.groupId,
                day: memoryData.day,
                hint: memoryData.hint || '',
                content: memoryData.content || '',
                reviewDays: memoryData.reviewDays || [1, 2, 4, 7, 14, 21, 28, 50],
                createTime: new Date().toISOString()
            });
            
            request.onsuccess = () => resolve(request.result);
            request.onerror = () => reject(new Error('添加记忆内容失败'));
        });
    }

    // 根据组ID获取记忆内容
    async getMemoriesByGroup(groupId) {
        const db = await this.ensureDB();
        const transaction = db.transaction(['memories'], 'readonly');
        const store = transaction.objectStore('memories');
        const index = store.index('groupId');
        
        return new Promise((resolve, reject) => {
            const request = index.getAll(groupId);
            request.onsuccess = () => resolve(request.result);
            request.onerror = () => reject(new Error('获取记忆内容失败'));
        });
    }

    // 根据记忆ID获取单个记忆内容
    async getMemory(memoryId) {
        const db = await this.ensureDB();
        const transaction = db.transaction(['memories'], 'readonly');
        const store = transaction.objectStore('memories');
        
        return new Promise((resolve, reject) => {
            const request = store.get(memoryId);
            request.onsuccess = () => resolve(request.result);
            request.onerror = () => reject(new Error('获取记忆内容失败'));
        });
    }

    // 根据组ID和天数获取记忆内容
    async getMemoryByGroupAndDay(groupId, day) {
        const db = await this.ensureDB();
        const transaction = db.transaction(['memories'], 'readonly');
        const store = transaction.objectStore('memories');
        const index = store.index('groupDay');
        
        return new Promise((resolve, reject) => {
            const request = index.get([groupId, day]);
            request.onsuccess = () => resolve(request.result);
            request.onerror = () => reject(new Error('获取记忆内容失败'));
        });
    }

    // 更新记忆内容
    async updateMemory(memoryId, updateData) {
        const db = await this.ensureDB();
        const transaction = db.transaction(['memories'], 'readwrite');
        const store = transaction.objectStore('memories');
        
        return new Promise((resolve, reject) => {
            const getRequest = store.get(memoryId);
            getRequest.onsuccess = () => {
                const memory = getRequest.result;
                if (memory) {
                    Object.assign(memory, updateData);
                    const putRequest = store.put(memory);
                    putRequest.onsuccess = () => resolve(putRequest.result);
                    putRequest.onerror = () => reject(new Error('更新记忆内容失败'));
                } else {
                    reject(new Error('记忆内容不存在'));
                }
            };
            getRequest.onerror = () => reject(new Error('获取记忆内容失败'));
        });
    }

    // 删除记忆内容
    async deleteMemory(memoryId) {
        const db = await this.ensureDB();
        const transaction = db.transaction(['memories'], 'readwrite');
        const store = transaction.objectStore('memories');
        
        return new Promise((resolve, reject) => {
            const request = store.delete(memoryId);
            request.onsuccess = () => resolve();
            request.onerror = () => reject(new Error('删除记忆内容失败'));
        });
    }

    // 清空所有数据
    async clearAll() {
        const db = await this.ensureDB();
        const transaction = db.transaction(['groups', 'memories'], 'readwrite');
        const groupStore = transaction.objectStore('groups');
        const memoryStore = transaction.objectStore('memories');
        
        return new Promise((resolve, reject) => {
            const groupRequest = groupStore.clear();
            const memoryRequest = memoryStore.clear();
            
            let completed = 0;
            const checkComplete = () => {
                completed++;
                if (completed === 2) {
                    resolve();
                }
            };
            
            groupRequest.onsuccess = checkComplete;
            groupRequest.onerror = () => reject(new Error('清空组数据失败'));
            memoryRequest.onsuccess = checkComplete;
            memoryRequest.onerror = () => reject(new Error('清空记忆数据失败'));
        });
    }
}

// 创建全局数据库实例
const db = new MemoryDatabase();

// 初始化数据库
async function initDatabase() {
    try {
        await db.init();
        console.log('数据库初始化成功');
    } catch (error) {
        console.error('数据库初始化失败:', error);
        throw error;
    }
}
